package com.example.coupon.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 通用的抽象过滤器类
 * @author wangbo
 * @description:
 * @date 2021/1/2915:30
 */
public abstract class AbstractZuulFilter extends ZuulFilter {

    //用于过滤器之间传递消息，数据保存在每个请求的ThreadLocal中
    //扩展了Map
    RequestContext context;

    private final static String NEXT = "next";

    @Override
    public String filterType() {
        return null;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        return (boolean) currentContext.getOrDefault(NEXT,true);
    }

    @Override
    public Object run() throws ZuulException {
        context = RequestContext.getCurrentContext();
        return cRun();
    }

    protected abstract Object cRun();

    Object fail(int code,String msg){
        context.set(NEXT,false);
        context.setSendZuulResponse(false);
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setResponseBody(String.format("{\"result\":\"%s!\"}",msg));
        return null;
    }

    Object success(){
        context.set(NEXT,true);
        return null;
    }
}
